<?php

namespace App\Service;

use App\Models\Call;
use App\Models\Cdr;
use App\Models\Gateway;
use App\Models\Queue;
use App\Models\Sip;
use App\Models\Task;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class CallcenterListenAleg
{
    //通话记录对象
    public $call;
    public $task;
    public $fs;

    public function __construct($call, $task)
    {
        $this->call = $call;
        $this->task = $task;
        $this->fs = new SwooleFreeswitch();
        if (!$this->fs->connect()) {
            return false;
        }

    }

    public function run()
    {
        $record_url = config('freeswitch.record_url');
        $fs_dir = '/usr/local/freeswitch';

        //更新为正在呼叫
        $this->call->update([
            'status' => 2,
            'aleg_uuid' => uuid_generate(),
            'datetime_originate_phone' => date('Y-m-d H:i:s')
        ]);
        Log::info("更新号码: " . $this->call->phone . " 状态为：2");

        $phone = $this->task->gateway->prefix ? $this->task->gateway->prefix . $this->call->phone : $this->call->phone;
        $varStr = "{origination_uuid=" . $this->call->aleg_uuid . "}";
        $varStr = "{originate_timeout=" . $this->task->max_wait_time . "}";
        if ($this->task->gateway->outbound_caller_id) {
            $varStr .= "{origination_caller_id_number=" . $this->task->gateway->outbound_caller_id . "}";
            $varStr .= "{origination_caller_id_name=" . $this->task->gateway->outbound_caller_id . "}";
        }
        $dail_string = "originate " . $varStr . "sofia/gateway/gw" . $this->task->gateway->id . "/" . $phone . " &echo()";
        Log::info("呼叫：" . $dail_string);

        $this->fs->bgapi($dail_string);
        $this->fs->events("CHANNEL_ANSWER CHANNEL_HANGUP_COMPLETE");
        $this->fs->filteruuid($this->call->aleg_uuid);

        while (true) {
            $received_parameters = $this->fs->recvEvent();
            if (!empty($received_parameters)) {
                $json = $this->fs->serialize($received_parameters);
                $eventname = Arr::get($json, 'Event-Name', null);
                $uuid = Arr::get($json, "CC-Member-Session-UUID");
                switch ($eventname) {
                    case 'CHANNEL_ANSWER':
                        $this->call->update([
                            'datetime_entry_queue' => date('Y-m-d H:i:s'),
                            'status' => 3
                        ]);
                        // 推送到队列
                        Queue::create([
                            'task_id' => $this->task->id,
                            'call_id' => $this->call->id,
                        ]);
                        break;
                    case 'CHANNEL_HANGUP_COMPLETE':
                        $this->call->refresh();
                        if ($this->call->datetime_sip_answer == null && $this->call->datetime_end == null){
                            $this->call->update([
                                'datetime_end' => date('Y-m-d H:i:s'),
                                'status' => 3
                            ]);
                        }
                        Queue::query()->where('call_id',$this->call->id)->delete();
                        if ($this->call->sip_id){
                            Sip::query()->where('id',$this->call->sip_id)->update(['state'=>'down']);
                        }
                        break 2;
                    default:
                        break;
                }
            }
        }
        $this->fs->disconnect();
    }

}
